import 'package:flutter/material.dart';
import 'package:jitsi_meet_flutter_sdk/jitsi_meet_flutter_sdk.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Jitsi Meet Flutter SDK Sample',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Jitsi Meet Flutter SDK Sample'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final meetingNameController = TextEditingController();
  final userNameController = TextEditingController();
  final jitsiMeet = JitsiMeet();
  bool _isInMeeting = false;

  @override
  void initState() {
    super.initState();
    // 设置默认房间名和用户名
    meetingNameController.text =
        "FlutterJitsiMeet${DateTime.now().millisecondsSinceEpoch}";
    userNameController.text = "用户${DateTime.now().millisecondsSinceEpoch}";
  }

  // 请求权限
  Future<bool> _requestPermissions() async {
    // 请求摄像头权限
    var cameraStatus = await Permission.camera.request();
    // 请求麦克风权限
    var microphoneStatus = await Permission.microphone.request();

    return cameraStatus.isGranted && microphoneStatus.isGranted;
  }

  void join() async {
    try {
      // 请求权限
      bool hasPermissions = await _requestPermissions();
      if (!hasPermissions) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text("需要摄像头和麦克风权限才能加入会议")));
        return;
      }

      String roomName = meetingNameController.text.trim();
      String userName = userNameController.text.trim();

      if (roomName.isEmpty) {
        roomName = "FlutterJitsiMeet${DateTime.now().millisecondsSinceEpoch}";
      }
      if (userName.isEmpty) {
        userName = "用户${DateTime.now().millisecondsSinceEpoch}";
      }
      var options = JitsiMeetConferenceOptions(
        serverURL: "https://meet.jit.si",
        room: roomName,
        configOverrides: {
          "startWithAudioMuted": false,
          "startWithVideoMuted": false,
          "subject": "Flutter Jitsi Meet 会议",
          "localSubject": "本地 Flutter Jitsi Meet 会议",
        },
        featureFlags: {
          "unsaferoomwarning.enabled": false,
          "security-options.enabled": false,
        },
        userInfo: JitsiMeetUserInfo(
          displayName: userName,
          email: "user@example.com",
        ),
      );

      print("正在加入会议: $roomName");
      jitsiMeet.join(options);

      // 更新状态
      setState(() {
        _isInMeeting = true;
      });

      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text("正在加入会议...")));
    } catch (e) {
      print("加入会议失败: $e");
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text("加入会议失败: $e")));
    }
  }

  void leave() {
    jitsiMeet.hangUp();
    setState(() {
      _isInMeeting = false;
    });
    ScaffoldMessenger.of(
      context,
    ).showSnackBar(const SnackBar(content: Text("已离开会议")));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            // 会议状态显示
            if (_isInMeeting)
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.green.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.green),
                ),
                child: const Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.videocam, color: Colors.green),
                    SizedBox(width: 8),
                    Text(
                      '正在会议中...',
                      style: TextStyle(
                        color: Colors.green,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              )
            else
              const SizedBox(height: 20),

            // 房间名称输入框
            SizedBox(
              width: 300,
              child: TextField(
                controller: meetingNameController,
                decoration: const InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: '输入会议房间名称',
                  labelText: '房间名称',
                  prefixIcon: Icon(Icons.video_call),
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 用户名称输入框
            SizedBox(
              width: 300,
              child: TextField(
                controller: userNameController,
                decoration: const InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: '输入您的显示名称',
                  labelText: '您的姓名',
                  prefixIcon: Icon(Icons.person),
                ),
              ),
            ),
            const SizedBox(height: 20),

            // 按钮行
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                // 加入会议按钮
                SizedBox(
                  width: 150,
                  height: 50,
                  child: FilledButton.icon(
                    onPressed: _isInMeeting ? null : join,
                    icon: const Icon(Icons.video_call),
                    label: Text(_isInMeeting ? '会议中' : '加入会议'),
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all(
                        _isInMeeting ? Colors.grey : Colors.blue,
                      ),
                      shape: MaterialStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ),
                      ),
                    ),
                  ),
                ),

                // 离开会议按钮
                SizedBox(
                  width: 150,
                  height: 50,
                  child: FilledButton.icon(
                    onPressed: _isInMeeting ? leave : null,
                    icon: const Icon(Icons.exit_to_app),
                    label: const Text('离开会议'),
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all(
                        _isInMeeting ? Colors.red : Colors.grey,
                      ),
                      shape: MaterialStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10.0),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
